import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_list_view.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_mains_elec_detail/keep_aliver_wrapper.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';

class SiteElecPriceSettingController extends GetxController
    with GetTickerProviderStateMixin {
  late TabController tabController;

  late RefreshController currentRefreshController;

  TextEditingController textController = TextEditingController();

  // 标题
  String title = ResKey.siteOverviewElectricitySetting.tr;

  List<String> allTabs = [
    ResKey.siteSettingElectricityPrice.tr,
    ResKey.siteSettingStoreDischargePrice.tr,
    ResKey.siteSettingPhotovoltaicPrice.tr,
    ResKey.siteSettingChargePrice.tr,

  ];
  List<String> tabs = [];
  GlobalKey<SiteListViewState> mainsKey = GlobalKey<SiteListViewState>();
  GlobalKey<SiteListViewState> internetKey = GlobalKey<SiteListViewState>();
  GlobalKey<SiteListViewState> chargeIdKey = GlobalKey<SiteListViewState>();
  GlobalKey<SiteListViewState> storeKey = GlobalKey<SiteListViewState>();
  late int siteId;
  // 1光伏站点 2儲能站点  、3充电站点，   光储站点，"12"，（”光储充站点”，"123"），（储充站点，23) 光充站点13
  var energyOptions = '';
  var monetaryUnitName = '';
  bool electricityPermission = true; //市电电价权限
  bool photovoltaicPricePermission = true; //光伏电价权限
  bool storeDischargePricePermission = true; //储能放电电价权限
  bool chargePricePermission = true; //充电电价权限
  bool isShowAdd = true; //是否显示新增按钮
  List <Widget> tabViews = [];
  final SiteServices siteServices = Get.find<SiteServices>();
  @override
  void onInit() {
    if (Get.arguments != null) {
      siteId = Get.arguments['siteId'];
      energyOptions = Get.arguments['energyOptions'];
      if(Get.arguments['monetaryUnitName'] != null){
        monetaryUnitName = Get.arguments['monetaryUnitName'];
      }
    }
    // electricityPermission = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingElectricitySettingGridDetail]);
    // photovoltaicPricePermission = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingElectricitySettingPvDetail]);
    // storeDischargePricePermission = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingElectricitySettingEssDetail]);
    // chargePricePermission = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingElectricitySettingChargeDetail]);
    if(electricityPermission){
      tabs.add(allTabs[0]);
      tabViews. add(KeepAliveWrapper(SiteListView(
        siteId: siteId,
        key: mainsKey,
        service: siteServices.getSiteMains,
        monetaryUnitName:monetaryUnitName,
        type: $enumDecodeNullable($ElecPriceTypeEnumMap, 0),
        index: 0,
      )));
    }
    if(energyOptions.contains('1') && photovoltaicPricePermission){
      tabs.add(allTabs[2]);
      tabViews. add(KeepAliveWrapper(SiteListView(
        siteId: siteId,
        key: internetKey,
        monetaryUnitName:monetaryUnitName,
        service: siteServices.getSiteInternet,
        type: $enumDecodeNullable($ElecPriceTypeEnumMap, 1),
        index: 1,
      )));
    }
    if(energyOptions.contains('2') && storeDischargePricePermission){
      tabs.add(allTabs[1]);
      tabViews. add(KeepAliveWrapper(SiteListView(
        siteId: siteId,
        key: storeKey,
        monetaryUnitName:monetaryUnitName,
        service: siteServices.getStoreDischarge,
        type: $enumDecodeNullable($ElecPriceTypeEnumMap, 3),
        index: 3,
      )));
    }
    if(energyOptions.contains('3') && chargePricePermission){
      tabs.add(allTabs[3]);
      tabViews. add(KeepAliveWrapper(SiteListView(
        siteId: siteId,
        key: chargeIdKey,
        monetaryUnitName:monetaryUnitName,
        service: siteServices.getSiteCharge,
        type: $enumDecodeNullable($ElecPriceTypeEnumMap, 2),
        index: 2,
      )));
    }
    tabController = TabController(length: tabs.length, vsync: this);
    tabController.addListener(() {
      if(tabController.index == tabController.animation?.value) {
        Log.d('addListener===' + tabController.index.toString());
        // if(tabController.index == 0){
        //   isShowAdd = true;
        // }else{
        //   isShowAdd = false;
        // }
        handleTabIndex();
        update();
      }
      // update();

    });
    Log.d('addListener===' + tabController.index.toString());
    handleTabIndex();
    super.onInit();
  }

  handleTabIndex(){
    Log.d('_handleTabIndex===' + tabs[tabController.index].toString());
    if(tabs[tabController.index] == ResKey.siteSettingElectricityPrice.tr){

      if(!electricityPermission){
        isShowAdd = true;
      }else{
        isShowAdd = false;
      }

    }else if(tabs[tabController.index] == ResKey.siteSettingStoreDischargePrice.tr){
      if(storeDischargePricePermission){
        isShowAdd = true;
      }else{
        isShowAdd = false;
      }
    }else if(tabs[tabController.index] == ResKey.siteSettingPhotovoltaicPrice.tr){
      if(photovoltaicPricePermission){
        isShowAdd = true;
      }else{
        isShowAdd = false;
      }

    }
    else if(tabs[tabController.index] == ResKey.siteSettingChargePrice.tr){
      if(photovoltaicPricePermission){
        isShowAdd = true;
      }else{
        isShowAdd = false;
      }
    }
    Log.d('isShowAdd===' + isShowAdd.toString());
    // update();
  }
  @override
  void onReady() {}

  ///新增市电电价,光伏电价.充电桩计费
  addNewElecPriceRule(){
    if(tabController.index == 0){//新增市电电价
      Get.toNamed(RouterPath.addMainsElectricityPrice,arguments: siteId)?.then((value){
        if(value ==true){
          refreshMains();
        }
      });
    }else if(tabs[tabController.index] == ResKey.siteSettingStoreDischargePrice.tr){//储能用电电价
      Map<String,dynamic> arguments = {'siteId': siteId,'isEnableEdit':true};
      Get.toNamed(RouterPath.energyStoreageDischargePriceController,arguments: arguments)?.then((value){
        Log.d('==value==' + value.toString());
        if(value ==true){
          refreshStoreEnergy();
        }
      });
    }else if(tabs[tabController.index] == ResKey.siteSettingPhotovoltaicPrice.tr){//新增光伏电价
      Get.toNamed(RouterPath.addPhotovoltaicPriceSet,arguments: siteId)?.then((value){
        if(value ==true){
          refreshInternet();
        }
      });
    }else if(tabs[tabController.index] == ResKey.siteSettingChargePrice.tr){//新增充电桩计费
      Get.toNamed(RouterPath.addChargePriceSet,arguments: siteId)?.then((value){
        if(value ==true){
          refreshCharge();
        }
      });
    }

  }
  Map<String, dynamic> setQueryParam() {
    Map<String, dynamic> extraParam = {
      'siteId': siteId,
      // 'id': keyWord
    };
    return extraParam;
  }

  reset(void Function(void Function()) setstate) {
    setstate(() {});
  }


  refresh({RefereshType refereshType = RefereshType.refresh}) {
    var index = tabController.index;
    switch (index) {
      case 0:
        refreshMains();
        break;
      case 1:
        refreshInternet();
        break;
      default:
        refreshCharge();
        break;
    }
  }

  refreshMains() {
    mainsKey.currentState?.extraParam = setQueryParam();
    mainsKey.currentState?.onRefresh();
  }
  refreshStoreEnergy() {
    storeKey.currentState?.extraParam = setQueryParam();
    storeKey.currentState?.onRefresh();
  }
  refreshInternet() {
    internetKey.currentState?.extraParam = setQueryParam();
    internetKey.currentState?.onRefresh();
  }

  refreshCharge() {
    chargeIdKey.currentState?.extraParam = setQueryParam();
    chargeIdKey.currentState?.onRefresh();
  }

  @override
  void onClose() {
    textController.dispose();
    tabController.dispose();
  }
}
